#include <emscripten/html5.h>
#include <emscripten.h>
#include <GLES2/gl2.h>
#include <EGL/egl.h>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <cassert>

// 结论：１个html页面上最多同时可以有16个(chrome:16; firefox:17)的glcontext


std::vector<EMSCRIPTEN_WEBGL_CONTEXT_HANDLE> vecContext;

void render() {
	for (auto itor=vecContext.begin(); itor!=vecContext.end(); ++itor){
		emscripten_webgl_make_context_current(*itor);
		auto r = (itor-vecContext.begin()) * 0.05f;
		glClearColor(r, 0.5f, 0.5f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);
	}	
}

EMSCRIPTEN_WEBGL_CONTEXT_HANDLE createCanvas(int idx){
	EM_ASM({
		var id = "c"+$0;
		var c = document.createElement("canvas");
		c.id = id;
		c.style = "width:50px;height:50px;margin:4px;border:1px solid black";
		document.body.appendChild(c);
	}, idx);

	EmscriptenWebGLContextAttributes attribs;
	emscripten_webgl_init_context_attributes(&attribs);
	attribs.alpha = false;
	attribs.enableExtensionsByDefault = false;
	attribs.preserveDrawingBuffer = true;		// 告诉 浏览器 swapbuffers 时 是 "拷贝" 而不是 "交换"
	char selecor[16]; sprintf(selecor, "#c%d", idx);
	auto context = emscripten_webgl_create_context(selecor, &attribs);
	assert(context);

	return context;
}



int main(){

	for (int i=0; i<20; ++i){
		vecContext.push_back(createCanvas(i));
	}
	
	emscripten_set_main_loop(render, 0, true);
}